%%%-------------------------------------------------------------------
%%% @author admin
%%% @copyright (C) 2022, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 06. 六月 2022 18:18
%%%-------------------------------------------------------------------
-module(db_load).
-author("admin").

-include("player.hrl").
-include("db_load.hrl").

%% record
-export([
    load/2,
    save/3
]).

%% kv
-export([
    mult_kv_save/2,
    mult_kv_load/2,
    mutl_kv_all_load/1
]).


%% ===================================================
%% 用于record存储
save(Name, Id, Record) ->
    Mod = name_mod(Name),
    case Mod:save(Record) of
        {ok, Data} ->
            case query(multi_hset, Name, Id, Data) of
                {ok, _} -> ok;
                Err -> {error, Err}
            end;
        Err -> Err
    end.

load(Name, Id) ->
    Mod = name_mod(Name),
    Fields = Mod:fields(),
    case query(multi_hget, Name, Id, [list_to_binary(atom_to_list(Field))||Field <- Fields]) of
        {ok, FieldData} ->
            Mod:load(FieldData);
        Err ->
            {error, Err}
    end.
%% ====================================================
%% 用于kv存储
mult_kv_save(Name, SaveData) ->
    TableName = list_to_binary(atom_to_list(Name)),
    Mod = name_mod(Name),
    case Mod:save(SaveData) of
        {ok, Data} ->
            case query(multi_hset, TableName, Data) of
                {ok, _} -> ok;
                Err -> {error, Err}
            end;
        Err -> Err
    end.

mult_kv_load(Name, Keys) ->
    TableName = list_to_binary(atom_to_list(Name)),
    Mod = name_mod(Name),
    case query(multi_hget, TableName, Keys) of
        {ok, LoadData} ->
            Mod:load(LoadData);
        Err ->
            {error, Err}
    end.

mutl_kv_all_load(Name) ->
    TableName = list_to_binary(atom_to_list(Name)),
    Mod = name_mod(Name),
    case query(scan, TableName, [<<"">>, <<"">>, 99999999]) of
        {ok, LoadData} ->
            Mod:load(LoadData);
        Err ->
            {error, Err}
    end.


%% ssdb访问
%%query(Cmd, TableName, Data) ->
%%    ssdb:query([Cmd, TableName| Data]).
%%
%%query(Cmd, TableName, Id, Data) ->
%%    TableNameFull = list_to_binary(atom_to_list(TableName) ++ "|" ++ integer_to_list(Id)),
%%    query(Cmd, TableNameFull, Data).

%% ets访问
query(Cmd, TableName, Data) ->
    ets_db:query(Cmd, TableName, Data).

query(Cmd, TableName, Id, Data) ->
    TableNameFull = list_to_binary(atom_to_list(TableName) ++ "|" ++ integer_to_list(Id)),
    ets_db:query(Cmd, TableNameFull, Data).

% ======================================================================
name_mod(?TABLE_PLAYER)         ->      player_sl;
name_mod(?TABLE_ACCOUNT)        ->      account_sl;
name_mod(?TABLE_PUB_DATA)       ->      pub_data_sl;
name_mod(_) -> undef.